import { useState, useEffect, useRef, useMemo } from 'react';
import { TextWidget } from '@inbiz/react';
import { observer } from '@formily/react';
import Header from './Header';
import Left from './Left';
import Right from './Right';
import { getAppInfoByDomain, getAllLanguages } from './service';
import { formatSiteName } from './utils';
import './style.less';

const LangeManage = observer((props: any) => {
    const [sites, setSites] = useState<any[]>([]);
    const [allLangs, setAllLangs] = useState<any[]>([]);
    const [currentSite, setCurrentSite] = useState('0');
    const [selectedRow, setSelectedRow] = useState<any>(null);
    const leftRef = useRef<any>();
    const queryRef = useRef<any>();

    const currentSiteInfo = useMemo(() => {
        return sites?.find((item: { SiteType: string; }) => item?.SiteType == currentSite)
    }, [currentSite, sites]);

    useEffect(() => {
        getAllLanguages().then((res) => {
            setAllLangs(res);
        });
        getAppInfoByDomain().then((res) => {
            const _sites = res?.Sites?.map((item: any) => {
                return {
                    key: '' + item?.SiteType,
                    label: formatSiteName(item?.SiteType),
                    ...item,
                };
            }) || [];
            setSites([..._sites, { key: '3', label: <TextWidget>LangManage.processForm</TextWidget> }]);
            const webSite = _sites?.find((item: { SiteType: number }) => item?.SiteType == 0);
            leftRef?.current?.getTreeData(false, webSite, () => {
                queryRef?.current?.getLangData({
                    siteOutId: webSite?.OutId || '',
                    dataVersionId: webSite?.DataVersionId || '',
                    queryLanguageType: 0,
                    siteType: 1,
                });
            });
        });
    }, []);

    return (
        <div className='inbiz-lang-manage-wrapper'>
            <Header
                selectedRow={selectedRow}
                currentSite={currentSite}
                setCurrentSite={setCurrentSite}
                sites={sites}
                allLangs={allLangs}
                leftRef={leftRef}
                queryRef={queryRef}
                siteInfo={currentSiteInfo}
            />
            <div className='inbiz-lang-manage-body'>
                <Left
                    ref={leftRef}
                    queryRef={queryRef}
                    setSelectedRow={setSelectedRow}
                    siteInfo={currentSiteInfo}
                />
                <Right
                    ref={queryRef}
                    isForm={currentSite == '3'}
                    currentSite={currentSite}
                    selectedRow={selectedRow}
                    allLangs={allLangs}
                    siteInfo={currentSiteInfo}
                />
            </div>
        </div>
    )
});

export default LangeManage;